#!/bin/bash -x

kernel_rpm_package_dir=""
csv_mem_percentage=0
source /etc/os-release

usage () {
  set +x
  echo -e "\033[31m
Usage: $0 <-h|-d <dir-of-kernel-rpm-packages>> [-c <csv-mem-percentage>]

       -h,--help      Display this help message
       -d,--directory Specify the directory of kernel's rpm packages
       -c,--csv3      Specify the decimal value of the `csv_mem_percentage` kernel parameter
                      Valid range [0, 80]
\033[0m"
  set -x
}

if [ $# -eq 0 ]; then
  usage
  exit 1
fi

params=$(getopt -o hd:c: --long help,directory:,csv3: -- "$@")
if [ $? -ne 0 ]; then
  echo "[Error] cannot parse parameters"
  exit 1
fi

eval set -- "$params"

while true; do
  case "$1" in
  -h|--help)
    usage
    exit 0
    ;;
  -d|--directory)
    kernel_rpm_package_dir="$2"
    shift 2
    ;;
  -c|--csv3)
    csv_mem_percentage=$2
    shift 2
    ;;
  --)
    shift
    break
    ;;
  *)
    usage
    exit 1
    ;;
  esac
done

install_kernel_rpm_packages () {
  sudo rpm -ivh --force --nodeps ${kernel_rpm_package_dir}/*.rpm
}

install_kernel_rpm_packages

update_grub_kernel_cmdline () {
  coco_host_kernel_cmdline="kvm-amd.sev=1 kvm-amd.sev_es=1"
  if [ ${csv_mem_percentage} -ne 0 ]; then
    coco_host_kernel_cmdline="${coco_host_kernel_cmdline} csv_mem_percentage=${csv_mem_percentage}"
  fi
  sudo sed -i "s/^\(GRUB_CMDLINE_LINUX=\".*\)\"$/\1 ${coco_host_kernel_cmdline}\"/g" /etc/default/grub
  sudo grub2-mkconfig -o /boot/efi/EFI/$ID/grub.cfg
}

update_grub_kernel_cmdline
